// app/controller/wechatController.js
const Controller = require('egg').Controller;
const { getAccessToken } = require('../utils/tools');
const crypto = require('crypto');
const axios = require('axios');

class WechatController extends Controller {
    async validate() {

        const { ctx } = this;
        const { signature, timestamp, nonce, echostr } = ctx.query;
        const { token } = this.config.wechatConfig; // 从配置文件中读取 token
        const hash = crypto.createHash('sha1');
        const str = [token, timestamp, nonce].sort().join('');
        hash.update(str);
        const sha1 = hash.digest('hex');

        if (sha1 === signature) {
            ctx.body = echostr;
        } else {
            ctx.status = 403;
            ctx.body = 'Invalid request';
        }
    }
    async createMenu() {
        const { ctx } = this
        const accessToken = await getAccessToken()
        const menuData = {
            "button": [
                {
                    name: "view",
                    type: "德亿刷",
                    url: "https://361069y1s7.picp.vip/",
                },

            ]
        }
        const response = await axios.post(`https://api.weixin.qq.com/cgi-bin/menu/create?access_token=${accessToken}`, menuData);
        ctx.body = {
            data: response.data
        }
        // return response.data;

    }
    async auth() {
        const { ctx } = this;
        const { appId } = this.config.wechatConfig; // 从配置中读取 appId 和回调地址
        // console.log('222')
        const redirectUri = 'http://3i61e06917.qicp.vip/wechat/auth/callback';
        const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
        // 重定向到微信授权页面
        ctx.redirect(url);
    }
    async callback() {
        const { ctx } = this;
        const code = ctx.query.code;
        const { appId, appSecret, redirectUri } = this.config.wechatConfig;
        // 使用code获取access_token
        const res = await ctx.curl(`https://api.weixin.qq.com/sns/oauth2/access_token`, {
            method: 'POST',
            data: {
                appid: appId,
                secret: appSecret,
                code: code,
                grant_type: 'authorization_code',
            },
        });

        const data = JSON.parse(res.data);
        if (!data.access_token) {
            ctx.status = 500;
            ctx.body = '获取access_token失败';
            return;
        }

        // 使用access_token和openid获取用户信息
        const userInfoRes = await ctx.curl(`https://api.weixin.qq.com/sns/userinfo`, {
            method: 'GET',
            data: {
                access_token: data.access_token,
                openid: data.openid,
                lang: 'zh_CN',
            },
        });

        const userInfo = JSON.parse(userInfoRes.data);
        ctx.session.userInfo = userInfo;
        console.log(ctx.session.userInfo, 'ctx.session.userInfo')
        if (!userInfo) {
            ctx.status = 500;
            ctx.body = '获取用户信息失败';
            return;
        }

        // 登录用户，创建会话等操作
        // 假设我们已经成功登录用户，并拿到了用户在系统中的唯一标识，例如userId
        const userId = 'some-user-id';

        // 重定向到指定路由，例如用户主页
        ctx.redirect(`https://361069y1s7.picp.vip/#/login`);
    }
}

module.exports = WechatController;